package com.car.order.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.alipay.api.AlipayClient;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.car.commons.core.model.WoniuException;
import com.car.commons.core.util.JwtUtil;
import com.car.commons.web.util.RedisUtil;
import com.car.commons.web.util.StateUtil;
import com.car.commons.web.util.WebUtil;
import com.car.order.annotation.GoodsOrderLogAnnotation;
import com.car.order.dto.goodOrderInfo.GoodOrderInfoDto;
import com.car.order.dto.goodOrderInfo.PayOrderForm;
import com.car.order.entity.GoodOrderInfo;
import com.car.order.entity.GoodOrderLog;
import com.car.order.entity.form.goodOrderInfo.*;
import com.car.commons.core.model.Result;
import com.car.order.entity.param.goodsOrderInfo.GoodOrderInfoInsertParam;
import com.car.order.exception.goodsOrderInfo.GoodsOrderInfoException;
import com.car.order.exception.goodsOrderInfo.GoodsOrderInfoExceptionCode;
import com.car.order.service.GoodOrderLogService;
import com.car.order.util.GoodsOrderDescConstants;
import com.car.order.util.RefundUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;

import org.springframework.web.bind.annotation.*;
import com.car.order.service.GoodOrderInfoService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author 杜岷芫
 * @since 2024-08-28 19:00:13
 */
@RestController
@RequestMapping("/goodOrderInfo")
@Api(tags = "商品订单信息")
public class GoodOrderInfoController {

    @Resource
    private GoodOrderInfoService goodOrderInfoService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private AlipayClient alipayClient;
    @Resource
    private RefundUtil refundUtil;
    @Resource
    private GoodOrderLogService goodOrderLogService;

    /**
     * 分页查询
     *
     * @param form
     * @return
     */
    @ApiOperation(value = "分页查询")
    @PostMapping("/findPage.pt")
    public Result findPage(@RequestBody GoodOrderInfoFindPageForm form) {
        Page<GoodOrderInfoDto> result = goodOrderInfoService.findPage(form);
        return Result.getResult().setMsg("查询成功").setData(result);
    }

    /**
     * 根据用户id分页查询
     *
     * @param form
     * @return
     */
    @ApiOperation(value = "根据用户id分页查询")
    @PostMapping("/findPageByUserId")
    public Result findPageByUserId(@RequestBody GoodOrderInfoFindPageByUserIdForm form) {
        Page<GoodOrderInfoDto> result = goodOrderInfoService.findPageByUserId(form);
        return Result.getResult().setMsg("查询成功").setData(result);
    }

    /**
     * 列表查询
     *
     * @param form
     * @return
     */
    @ApiOperation(value = "列表查询")
    @PostMapping("/findList.pt")
    public Result findList(@RequestBody GoodOrderInfoFindListForm form) {
        List<GoodOrderInfo> result = goodOrderInfoService.findList(form);
        return Result.getResult().setMsg("查询成功").setData(result);
    }

    /**
     * 查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据订单id查询详情")
    @GetMapping("/{id}.ty")
    public Result findById(@PathVariable("id") String id) {
        GoodOrderInfo goodOrderInfo = goodOrderInfoService.findById(id);
        return Result.getResult().setMsg("查询成功").setData(goodOrderInfo);
    }

    /**
     * 新增
     *
     * @param form
     * @return
     */
    @ApiOperation(value = "新增-生成订单")
    @PostMapping
    public Result insert(@RequestBody GoodOrderInfoInsertForm form) throws Exception {
        String token = WebUtil.getRequest().getHeader("car-token");
        Integer userId = JwtUtil.getUserId(token);
        GoodOrderInfoInsertParam param = BeanUtil.toBean(form, GoodOrderInfoInsertParam.class);
        param.setUserId(userId);
        GoodOrderInfoDto goodOrderInfo = goodOrderInfoService.insert(param);
        return Result.getResult().setMsg("操作成功").setData(goodOrderInfo);
    }

    /**
     * 支付订单
     *
     * @param form
     * @param token
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "支付订单")
    @PostMapping("/payOrder")
    public Result payOrder(@RequestBody PayOrderForm form, @RequestHeader("car-token") String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        Integer userId = JwtUtil.getUserId(token);
        String s = goodOrderInfoService.payOrder(form, userId);
        return Result.getResult().setMsg("跳转支付页面").setData(s);
    }

    /**
     * 支付宝回调接口
     *
     * @param req
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "支付宝回调接口")
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest req) throws Exception {
        HashMap<String, String> params = new HashMap<>();
        //获取支付宝请求的所有参数
        Map<String, String[]> reqParameterMap = req.getParameterMap();
        //通过迭代，获取所有
        for (Iterator<String> iterator = reqParameterMap.keySet().iterator(); iterator.hasNext(); ) {
            String name = iterator.next();
            String[] values = (String[]) reqParameterMap.get(name);//String[],因为value可能不只一个
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        goodOrderInfoService.payNotify(params);
        return "SUCCESS";
    }


    /**
     * 修改订单信息
     *
     * @param form
     * @return
     */
    @ApiOperation(value = "修改订单信息")
    @PutMapping
    public Result update(@RequestBody GoodOrderInfoUpdateForm form) {
        GoodOrderInfo goodOrderInfo = goodOrderInfoService.update(form);
        return Result.getResult().setMsg("操作成功").setData(goodOrderInfo);
    }

    /**
     * 修改订单状态
     *
     * @param form
     * @return
     */
    @ApiOperation(value = "修改订单状态")
    @PutMapping("/changeState")
    public Result changeState(@RequestBody GoodOrderInfoChangeStateForm form) {
        GoodOrderInfoDto goodOrderInfo = goodOrderInfoService.changeState(form);
        return Result.getResult().setMsg("操作成功").setData(goodOrderInfo);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        goodOrderInfoService.delete(id);
        return Result.getResult().setMsg("操作成功");
    }

    /**
     * 退款
     *
     * @param orderId
     * @return
     * @throws Exception
     */
    @GetMapping("/tuikuan/{orderId}.ty")
    @GoodsOrderLogAnnotation(desc = GoodsOrderDescConstants.USER_TUI_KUAN)
    public Result tuikuan(@PathVariable("orderId") String orderId) throws Exception {
        GoodOrderInfo byId = goodOrderInfoService.getById(orderId);
        if (byId == null) {
            throw new GoodsOrderInfoException(GoodsOrderInfoExceptionCode.GOODS_ORDER_INFO_NOT_EXIST);
        }
        refundUtil.refund(orderId);
        return Result.getResult().setMsg("退款成功");
    }

    /**
     * 换货
     */
    @GetMapping("/huanhuo.ty")
    @GoodsOrderLogAnnotation(desc = GoodsOrderDescConstants.USER_HUAN_HUO)
    public Result huanhuo(@RequestParam String orderId) {
        GoodOrderInfo byId = goodOrderInfoService.getById(orderId);
        if (byId == null) {
            throw new GoodsOrderInfoException(GoodsOrderInfoExceptionCode.GOODS_ORDER_INFO_NOT_EXIST);
        }
        byId.setOrderState(StateUtil.SERVE_ORDER_STATE_NOT_SERVED);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = LocalDateTime.now().format(formatter);
        byId.setOrderCreatTime(format);
        byId.setOrderPayTime(format);
        Snowflake snowflake = new Snowflake(1, 1);
        String idStr = snowflake.nextIdStr();
        byId.setGoodOrderId(idStr);
        goodOrderInfoService.save(byId);
//        //换货旧订单的日志
//        GoodOrderLog goodOrderLog = new GoodOrderLog();
//        goodOrderLog.setLogTime(format);
//        goodOrderLog.setGoodOrderId(orderId);
//        goodOrderLog.setLogDesc("用户进行换货，换货后的订单为" + idStr);
//        boolean save = goodOrderLogService.save(goodOrderLog);
//        if (!save) {
//            throw new WoniuException(500, "换货日志生成失败");
//        }
//
//        //换货新订单的日志
//        GoodOrderLog goodOrderLog1 = new GoodOrderLog();
//        goodOrderLog1.setLogTime(format);
//        goodOrderLog1.setGoodOrderId(idStr);
//        goodOrderLog1.setLogDesc("用户进行换货，换货后的订单为" + idStr);
//        boolean save1 = goodOrderLogService.save(goodOrderLog1);
//        if (!save1) {
//            throw new WoniuException(500, "换货日志生成失败");
//        }
        return Result.getResult().setData(idStr);
    }
}